﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.Services.Protocols;
using System.Net;
using System.Web.Hosting;
using System.IO;
using EnCor.ObjectBuilder;

namespace EnCor.Hosting.WSHosting
{
    [AssembleConfig(typeof(WSHostConfig))]
    public class WSHost : FacadeHost
    {
        WSFacadeHostConfig _Config;

        private HttpListenerWrapper _Listener;
        private WebServiceMapCollection _Maps;
        private string _EndPoint;

        public void Config(FacadeHostConfiguration config)
        {
            _Config = config as WSFacadeHostConfig;
            List<WebServiceMapItem> maplist = new List<WebServiceMapItem>();
            foreach (FacadeServiceConfig serviceConfig in _Config.Services)
            {
                maplist.Add(new WebServiceMapItem(serviceConfig.Url, serviceConfig.Type));
            }

            _Maps = new WebServiceMapCollection(maplist);
            _EndPoint = config.Endpoint;
        }

        public override void Start()
        {
            string[] prefixes = new string[] { _EndPoint };
            //throw new NotImplementedException();

            //RequestHandlerFactory handler = new RequestHandlerFactory(_Maps);
            //HttpListener listeren = new HttpListener(handler);
            //listeren.Listen(System.Net.IPAddress.Parse(_Config.Url), _Config.Port);

            HttpListenerWrapper listener = (HttpListenerWrapper)ApplicationHost.CreateApplicationHost(
                typeof(HttpListenerWrapper),
                "/",
                Directory.GetCurrentDirectory()
                );
            //HttpListenerWrapper listener = new HttpListenerWrapper();
            listener.Configure(prefixes, "/", Directory.GetCurrentDirectory(), _Maps);
            listener.Start();
            _Listener = listener;
        }

        public override void Stop()
        {
            if (_Listener != null)
            {
                _Listener.Stop();
            }
        }
    }
}
